package com.reindeer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reindeer.dto.ProductQueryRequest;
import com.reindeer.dto.ProductVO;
import com.reindeer.entity.Product;
import com.reindeer.mapper.ProductMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ProductService {
    
    private final ProductMapper productMapper;

    public Page<ProductVO> queryProducts(ProductQueryRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(request.getName())) {
            queryWrapper.like(Product::getName, request.getName());
        }
        
        if (StringUtils.hasText(request.getSource())) {
            queryWrapper.eq(Product::getSource, request.getSource());
        }
        
        // 分页查询
        Page<Product> page = new Page<>(request.getPage(), request.getSize());
        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);
        
        // 转换为VO
        List<ProductVO> productVOList = productPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<ProductVO> resultPage = new Page<>(productPage.getCurrent(), productPage.getSize(), productPage.getTotal());
        resultPage.setRecords(productVOList);
        
        return resultPage;
    }
    
    private ProductVO convertToVO(Product product) {
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);
        return vo;
    }
} 